<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
>
<head>
    <meta charset="utf-8">
    <title>欢迎使用mdms</title>

    <link th:href="@{/easyui/themes/default/easyui.css}" rel="stylesheet" type="text/css"/>
    <link th:href="@{/easyui/themes/icon.css}" rel="stylesheet" type="text/css"/>
    <link th:href="@{/easyui/demo/demo.css}" rel="stylesheet" type="text/css"/>
    <link th:href="@{/codemirror/codemirror.css}" rel="stylesheet" type="text/css"/>


    <script th:src="@{/easyui/jquery.min.js}" type="text/javascript"></script>
    <script th:src="@{/easyui/jquery.easyui.min.js}" type="text/javascript"></script>
    <script th:src="@{/codemirror/codemirror.js}" type="text/javascript"></script>
    <script th:src="@{/codemirror/sql.js}" type="text/javascript"></script>
    <script th:src="@{/codemirror/sql-hint.js}" type="text/javascript"></script>
    <script th:src="@{/fly/fly.js}" type="text/javascript"></script>
    <script th:src="@{/selfjs/FlyRequest.js}" type="text/javascript"></script>
    <script th:src="@{/commonjs/CommonParam.js}" type="text/javascript"></script>
    <style>
        .CodeMirror {
            border: 1px solid #cccccc;
            height: 98%;
        }
    </style>
</head>
<body class="easyui-layout">
<div data-options="region:'north',border:false" style="height:200px;">
    <div id="operator" class="panel-header panel-header-noborder  " style="padding:0px;height:auto">
        <div>
            <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-diy-run1" plain="true"
               onclick="run();">执行(F8)</a>

            <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-diy-clear1" plain="true"
               onclick="clearSQL()">清空(F7)</a>

            <a href="javascript:void(0)" class="easyui-menubutton" id="commonSqlBtn"
               iconCls="icon-diy-commonuse1"
               plain="true"
            >常用SQL</a>

        </div>
        <div id="myCommonSql">
        </div>
        <div style="width:100%;height:170px; ">
            <input type="hidden" id="searchHistoryId">
            <input type="hidden" id="searchHistoryName">
            <textarea id="sqltextarea" style="margin:10px; font-size:14px;font-family: '微软雅黑';width:98.5%;height:90%; ">
</textarea>
        </div>
    </div>
</div>
<div data-options="region:'center'" style="height:97%;padding:0px">
    <div id="searchTabs" class="easyui-tabs"
         data-options="fit: true, border: false, showOption: true, enableNewTabMenu: true, enableJumpTabMenu: true">
        <div id="searcHomePanel" data-options="title: '消息', iconCls: 'icon-tip'">

<textarea id="executeMessage" style="margin:10px; font-size:14px;font-family: '微软雅黑';width:98.5%;height:98%; " readonly>
</textarea>

        </div>
    </div>
</div>

<!-- 添加模块 -->
<div id="adddlg" class="easyui-dialog" style="width:600px;height:400px;padding:10px 20px"
     closed="true" closable="false" modal="true" buttons="#dlg-buttons">
    <form id="addfm" method="post" novalidate>
        <input name="id" type="hidden"/>
        <table cellpadding="5">
            <tr>
                <td>名称:</td>
                <td><input name="name" class="easyui-textbox" type="text" required="true" missingMessage="不能为空"/></td>
            </tr>
            <tr>
                <td>SQL:</td>
                <td>
                    <input id="commonSqlAdd" name="commonSql" style="width:100%;height:100%" required="true"
                           missingMessage="不能为空"/>
                </td>
            </tr>
        </table>
    </form>
</div>
<div id="dlg-buttons">
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel"
       onclick="javascript:$('#adddlg').dialog('close')">取消</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveAddFm()">保存</a>
</div>

<!-- 常用SQL管理模块 -->
<div id="commonSqlMngDlg" class="easyui-dialog" maximized="true"
     closed="true" closable="true" modal="true">
    <table id='commonSqlMngDg' style="width:100%;height:100%"></table>
</div>

<script type="text/javascript">
    let ctxPath = '[[${#servletContext.contextPath}]]';
    let resultTabCnt = 0;
    let commonSqlMapInPage = {};
    let commonSqlListInPage = {};

    let editor = CodeMirror.fromTextArea(document.getElementById("sqltextarea"), {
        lineNumbers: true,
        matchBrackets: true,
        hintOptions: {
            completeSingle: false,
            completeOnSingleClick: true
        },
        indentUnit: 4,
        mode: "text/x-mysql",
        lineWrapping: true,
        theme: "eclipse",
        autofocus: true,
        extraKeys: {
            ctrl: "autocomplete",
            F7: function () {
                clearSQL()
            }, F8: function () {
                run()
            }
        }
    });
    // //editor.on("inputRead", codemirrorAutocompleteOnInputRead);
    editor.refresh();
    editor.focus();
    // $(editor.getWrapperElement()).bind("keydown", catchKeypressesFromSqlTextboxes);
    // function catchKeypressesFromSqlTextboxes(a) {
    //     !a.ctrlKey || 13 != a.keyCode && 10 != a.keyCode || 0 < $("#sqltextarea").length || 0 < $("#sqltextarea").length && run()
    // }
    //
    let execMessage = CodeMirror.fromTextArea(document.getElementById("executeMessage"), {
        mode: "text/x-mysql",
        theme: "eclipse",
        lineNumbers: true,
        autofocus: false,
        readOnly: true
    });

    $(function () {
        $("#sqltextarea").val('');

        getCommonSql();

        $('#commonSqlAdd').textbox({
            multiline: true,
            width: 470,
            height: 230
        })
    });

    function run() {
        let runSql = $.trim(editor.getValue()),
            textSelected = editor.getSelection();
        if ('' != textSelected) {
            runSql = textSelected;
        }

        if ('' == runSql) {
            $.messager.show({
                title: '提示',
                msg: '请输入SQL语句',
                showType: 'show'
            });
            return;
        }

        let sqlList = [];
        let runSqlSplit = runSql.split(";");
        for (let a = 0; a < runSqlSplit.length; a++) {
            if ($.trim(runSqlSplit[a]) == '') {
                continue;
            }

            if ($.trim(runSqlSplit[a]).startsWith('select')
                || $.trim(runSqlSplit[a]).startsWith('SELECT')
                || $.trim(runSqlSplit[a]).startsWith('insert')
                || $.trim(runSqlSplit[a]).startsWith('INSERT')
                || $.trim(runSqlSplit[a]).startsWith('update')
                || $.trim(runSqlSplit[a]).startsWith('UPDATE')
                || $.trim(runSqlSplit[a]).startsWith('delete')
                || $.trim(runSqlSplit[a]).startsWith('DELETE')
            ) {
                sqlList.push($.trim(runSqlSplit[a]));
            } else {
                $.messager.show({
                    title: '提示',
                    msg: '只能执行select,insert,update,delete',
                    showType: 'show'
                });
                return;
            }
        }

        let submitData = {};
        submitData['sqlList'] = sqlList;

        postJSON(ctxPath + '/excuteAndShow/execSql', submitData,
            function (data) {
                let resultList = data['resultList'];
                for (let n = 1; n <= resultList.length; n++) {
                    $("#searchTabs").tabs("add", {
                        title: "结果" + n,
                        content: " <div id='pg" + n + "' style='height:30px' class='easyui-pagination'></div><div><table id='result" + n +
                            "' style='padding:0px;height:calc(100% - 30px);width:98.3%'></table></div>",
                        closable: true,
                        iconCls: "icon-diy-table1"
                    });

                    let toolbar = [{
                        text: '下载(最多1000条)',
                        iconCls: 'icon-diy-export1',
                        handler: function () {
                            exportData(resultList[n - 1]['sql']);
                        }
                    }];

                    let domResult = '#result' + n;
                    $(domResult).datagrid({
                        data: resultList[n - 1]['result']
                        , columns: [resultList[n - 1]['columns']]
                        , autoRowHeight: true
                        , rownumbers: true
                        , singleSelect: true
                        //, toolbar: toolbar
                    });

                    let domPg = '#pg' + n;
                    $(domPg).pagination({
                        pageList: COMMONPARAM_PAGELIST,
                        pageSize: resultList[n - 1]['pageSize'],
                        total: resultList[n - 1]['totalCount'],
                        pageNumber: resultList[n - 1]['pageNo'],
                        beforePageText: '第',
                        afterPageText: '页    共 {pages} 页',
                        displayMsg: '当前显示 {from} - {to}条记录,共{total}条记录',
                        onSelectPage: function (pageNumber, pageSize) {
                            pagingList(pageNumber, pageSize, resultList[n - 1]['sql'], domResult, domPg);//选择第几页的时候，就刷新
                        },
                    });

                    resultTabCnt++;
                }
                //alert(data['runLog']);
                execMessage.setValue(data['runLog']);
                execMessage.refresh();
            }, function (result, resultdesc) {
                $.messager.show({
                    title: '异常',
                    msg: result + '-' + resultdesc,
                    showType: 'show'
                });
            }, function () {
                alert(3)
            }, function () {
                $.messager.progress(COMMONPARAM_PROCESS);
                //开始前先关闭其它
                for (let n = 1; n <= resultTabCnt; n++) {
                    $("#searchTabs").tabs("close", '结果' + n);
                }
                resultTabCnt = 0;
            }, function () {
                $.messager.progress('close');
            });
    }

    function pagingList(pageNumber, pageSize, sql, domResult, domPg) {
        let submitData = {};
        submitData['sql'] = sql;
        //TODO:以后这里还得加查询条件等等
        submitData['page'] = pageNumber;
        submitData['limit'] = pageSize;
        postJSON(ctxPath + '/excuteAndShow/pagingList', submitData,
            function (data) {
                let pageResult = data['pageResult'];
                $(domResult).datagrid("loadData", pageResult['result']);
                $(domPg).pagination({
                    pageList: COMMONPARAM_PAGELIST,
                    pageSize: pageResult['pageSize'],
                    total: pageResult['totalCount'],
                    pageNumber: pageResult['pageNo'],
                    beforePageText: '第',
                    afterPageText: '页    共 {pages} 页',
                    displayMsg: '当前显示 {from} - {to}条记录,共{total}条记录',
                    onSelectPage: function (pageNumber, pageSize) {
                        pagingList(pageNumber, pageSize, pageResult['sql'], domResult, domPg);//选择第几页的时候，就刷新
                    },
                });
            }, function (result, resultdesc) {
                $.messager.show({
                    title: '异常',
                    msg: result + '-' + resultdesc,
                    showType: 'show'
                });
            }, function () {
                alert(3)
            }, function () {
                $.messager.progress(COMMONPARAM_PROCESS);
            }, function () {
                $.messager.progress('close');
            });
    }

    function exportData(sql) {
        alert(sql);
        let submitData = {};
        submitData['sql'] = sql;
        postJSON(ctxPath + '/excuteAndShow/exportData', submitData,
            function (data) {
                //这里拿到文件的路径，然后进行导出
                let excelName = data['excelName'];
                let str = ctxPath + '/excuteAndShow/downloadExportData?excelName=' + excelName;
                window.open(str);
            }, function (result, resultdesc) {
                $.messager.show({
                    title: '异常',
                    msg: result + '-' + resultdesc,
                    showType: 'show'
                });
            }, function () {
                alert(3)
            }, function () {
                $.messager.progress(COMMONPARAM_PROCESS);
            }, function () {
                $.messager.progress('close');
            });
    }

    function clearSQL() {
        editor.setValue('');
    }

    function addCommonSql() {
        COMMONPARAM_WEBOPERATION = 'add';
        $('#adddlg').dialog('open').dialog('setTitle', '添加常用SQL');
        $('#addfm').form('clear');
        $('#commonSqlAdd').textbox('setValue', editor.getValue());
    }

    function mngCommonSql() {
        $('#commonSqlMngDlg').dialog('open').dialog('setTitle', '常用SQL列表');
        let toolbar = [{
            text: '修改',
            iconCls: 'icon-diy-edit1',
            handler: function () {
                openEditCommonSqlDlg();
            }
        }, {
            text: '删除',
            iconCls: 'icon-diy-delete1',
            handler: function () {
                delCommonSql();
            }
        }];
        $('#commonSqlMngDg').datagrid({
            data: commonSqlListInPage
            , columns: [
                [
                    {field: 'id', title: 'id', resizable: true, hidden: true}
                    , {field: 'name', title: '名称', resizable: true}
                    , {field: 'commonSql', title: '常用SQL', resizable: true}
                ]
            ]
            , autoRowHeight: true
            , rownumbers: true
            , singleSelect: true
            , toolbar: toolbar
        });
    }

    function openEditCommonSqlDlg() {
        COMMONPARAM_WEBOPERATION = 'edit';
        let row = $('#commonSqlMngDg').datagrid('getSelected');
        if (row) {
            $('#adddlg').dialog('open').dialog('setTitle', '修改常用SQL');
            $('#addfm').form('load', row);
        } else {
            $.messager.show({
                title: '提示',
                msg: '请选择一条记录!',
                showType: 'show'
            });
        }
    }

    function saveAddFm() {
        if (!$('#addfm').form('validate')) {
            return;
        }

        let submitData = geneSubmitDataFromForm("#addfm", {});
        if (COMMONPARAM_WEBOPERATION == 'add') {
            delete submitData['id'];
        }
        postJSON(ctxPath + '/excuteAndShow/' + COMMONPARAM_WEBOPERATION + 'CommonSql', submitData,
            function (data) {
                $('#adddlg').dialog('close');
                $.messager.show({
                    title: '提示',
                    msg: '编辑常用SQL成功',
                    showType: 'show'
                });
                //getCommonSql();
                //TODO:上面的刷新没用，先直接刷新页面好了
                window.location = '/excuteAndShow/loadPage';
            }, function (result, resultdesc) {
                $.messager.show({
                    title: '异常',
                    msg: result + '-' + resultdesc,
                    showType: 'show'
                });
            }, function () {
                alert(3)
            }, function () {
                $.messager.progress(COMMONPARAM_PROCESS);
            }, function () {
                $.messager.progress('close');
            });
    }

    function delCommonSql() {
        COMMONPARAM_WEBOPERATION = 'del';
        let row = $('#commonSqlMngDg').datagrid('getSelected');
        if (row) {
            $.messager.confirm('提示', '你确定要删除该条记录?', function (r) {
                if (r) {
                    let submitData = {};
                    submitData['id'] = row['id'];
                    postJSON(ctxPath + '/excuteAndShow/' + COMMONPARAM_WEBOPERATION + 'CommonSql', submitData,
                        function (data) {
                            $.messager.show({
                                title: '提示',
                                msg: '删除常用SQL成功',
                                showType: 'show'
                            });
                            //getCommonSql();
                            //TODO:上面的刷新没用，先直接刷新页面好了
                            window.location = '/excuteAndShow/loadPage';
                        }, function (result, resultdesc) {
                            $.messager.show({
                                title: '异常',
                                msg: result + '-' + resultdesc,
                                showType: 'show'
                            });
                        }, function () {
                            alert(3)
                        }, function () {
                            $.messager.progress(COMMONPARAM_PROCESS);
                        }, function () {
                            $.messager.progress('close');
                        });
                }
            });
        } else {
            $.messager.show({
                title: '提示',
                msg: '请选择一条记录!',
                showType: 'show'
            });
        }
    }

    function getCommonSql() {
        let submitData = {};
        postJSON(ctxPath + '/excuteAndShow/getCommonSql', submitData,
            function (data) {
                commonSqlMapInPage = {};
                $('#myCommonSql').html('');
                let myCommonSqlDiv = "<div id= 'mm' style='display:none'>";
                let list = data['list'];
                commonSqlListInPage = list;
                myCommonSqlDiv += "<div>";
                myCommonSqlDiv += "<span>选择</span>";
                myCommonSqlDiv += "<div>";
                for (let i = 0; i < list.length; i++) {
                    myCommonSqlDiv += "<div onclick='addCommonSqlToEditor(\"" + list[i]['id'] + "\")'>";
                    myCommonSqlDiv += list[i]['name'];
                    myCommonSqlDiv += "</div>";
                    commonSqlMapInPage[list[i]['id']] = list[i];
                }
                myCommonSqlDiv += "</div>";
                myCommonSqlDiv += "</div>";
                myCommonSqlDiv += "<div onclick='addCommonSql()'>添加</div>";
                myCommonSqlDiv += "<div onclick='mngCommonSql()'>管理</div>";
                myCommonSqlDiv += "</div>";
                $('#myCommonSql').html(myCommonSqlDiv);
                $('#commonSqlBtn').menubutton({
                    iconCls: 'icon-diy-commonuse1',
                    menu: '#mm'
                });
            }, function (result, resultdesc) {
                $.messager.show({
                    title: '异常',
                    msg: result + '-' + resultdesc,
                    showType: 'show'
                });
            }, function () {
                alert(3)
            }, function () {
                $.messager.progress(COMMONPARAM_PROCESS);
            }, function () {
                $.messager.progress('close');
            });
    }

    function addCommonSqlToEditor(commonSqlId) {
        let editorValue = editor.getValue();
        if ('' != $.trim(editorValue)) {
            editorValue += '\r\n';
            editorValue += '\r\n';
        }
        editorValue += commonSqlMapInPage[commonSqlId]['commonSql'];
        editor.setValue(editorValue);
    }

</script>
</body>